import { Module } from 'vuex'
import { ILoginState } from './type'
import { IRootState } from '@/store/type'
import { $login, $select } from '@/service/common'
import { mapMenusToRoutes } from '@/utils/map-menus'
import router from '@/router'

const loginModule: Module<ILoginState, IRootState> = {
  namespaced: true,
  state() {
    return {
      agentCodeArr: [],
      userMenus: []
    }
  },
  mutations: {
    changeAgentCodeArr(state, arr: any) {
      state.agentCodeArr = arr
    },
    changeUserMenus(state, userMenus: any) {
      state.userMenus = userMenus
      const routes = mapMenusToRoutes(userMenus)
      for (const route of routes) {
        router.addRoute('index', route)
      }
    }
  },
  actions: {
    async getAgentCodeArr({ commit }) {
      const result = localStorage.getItem('agentCodeArr') ?? ''
      const token = localStorage.getItem('token')
      if (!result && token) {
        const { data } = await $select.select()
        localStorage.setItem('agentCodeArr', JSON.stringify(data))
        return commit('changeAgentCodeArr', data)
      }
      result && commit('changeAgentCodeArr', JSON.parse(result))
    },
    async getMenuArr({ commit }) {
      const result = localStorage.getItem('menuArr') ?? ''
      if (result) return commit('changeUserMenus', JSON.parse(result))
      $login
        .getMenu()
        .then((res) => {
          const data = res.data
          const menuArr = []
          let record = null
          for (const item of data) {
            if (item.parentId === '0') {
              item.children = []
              menuArr.push(item)
              record = item
            } else {
              record.children?.push(item)
            }
          }
          commit('changeUserMenus', menuArr)
          localStorage.setItem('menuArr', JSON.stringify(menuArr))
        })
        .catch((err) => {
          console.log(err)
        })
    }
  },
  getters: {
    agentCodes(state) {
      return state.agentCodeArr.map((item) => {
        item.title = item.name
        item.value = item.agentCode
        return item
      })
    }
  }
}

export default loginModule
